package org.sibframework.utils;

import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.Properties;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;

public class PropertiesFileUtils {
	public Properties loadProperties(String propFile) throws IOException {
		InputStream is = this.getClass().getClassLoader().getResourceAsStream(propFile);
		return loadProperties(is);
		
	}
	
	public Properties loadProperties(InputStream is) throws IOException {
		//load from properties files
        Properties prop = new Properties();
        prop.load(is);

        return prop;
	}
	
	public Object loadProperties(String propFile, Object object) throws IOException {
		Properties prop = this.loadProperties(propFile);
		this.feedObject(prop, object);
		return object;
	}
	
	public void feedObject(Properties prop, Object object) {
		for (PropertyDescriptor pd : PropertyUtils.getPropertyDescriptors(object)) {
			String value = prop.getProperty(pd.getName());
			if (value != null) {
				try {
					BeanUtils.setProperty(object, pd.getName(), value);
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
